package com.sprite.framework.start.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.w3c.dom.Element;

import com.sprite.utils.UtilURL;

public class ContainerUtils {
	private final static String START_CONFIG = "start.config";

	private final static String DEFAULT_START_CONFIG = "start.xml";

	public static URL readConfigUrl() {
		String configPath = System.getProperty(START_CONFIG);
		configPath = configPath == null ? DEFAULT_START_CONFIG : configPath;

		URL url = UtilURL.fromResource(configPath);
		if(url == null) {
			configPath = "conf/start.xml";
			url = UtilURL.fromResource(configPath);
		}

		if(url == null) {
			configPath = "build/conf/start.xml";

			url = UtilURL.fromResource(configPath);
		}

		if(url == null) {
			configPath = "config/start.xml";
			url = UtilURL.fromResource(configPath);
		}

		return url;
	}

	
	public static String readContent(InputStream inputStream) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

		StringBuilder content = new StringBuilder();
		String line = null;
		while((line =bufferedReader.readLine()) != null ) {
			content.append(line);
		}
		
		return content.toString();
	}
	
	public static String getPropertyValue(Element element) {
		String value = element.getAttribute("value");
		if(value == null) {
			value = element.getTextContent();
		}else {
			value = value.trim();
		}
		
		if("true".equals(element.getAttribute("tpl"))) {
			Tpl tpl  = new Tpl(value.trim());
			return tpl.getValue();
		}
		
		return value;
	}
	
	public static String getPropertyKey(Element element) {
		return element.getAttribute("key");
	}
}
